<script setup lang='ts' name="org-add-user">
import type { FormInstance } from 'element-plus'
import { distributeArea, distributeCard, getCardList, getCompanyById } from '@fl/api/joint-api'
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus'
import { toRefs } from 'vue'
import { useRule } from './hooks/use-rule'

const props = defineProps<{
    // data: any
    modelValue: boolean
    showId?: string
}>()
const emits = defineEmits(['update:modelValue', 'confirm'])
const { showId } = toRefs(props)
console.log('🚀 ~ showId:', showId)
const loading = ref(true)
const idList = computed(() => {
    return showId.value?.includes(',') ? showId.value.split(',') : [showId.value]
})

const { modelValue } = toRefs(props)

const { appRules } = useRule()

const form = ref<any>({})
const formRef = ref()

const cardList = ref<any>([])

async function getList() {
    const res = await getCardList()
    cardList.value = res?.list.map(item => ({
        id: String(item.id),
        name: item.name,
        appKey: item.appKey,
        appId: item.appId,
    })) || []
}
onMounted(async () => {
    loading.value = true
    await getList()
    const res = await getCompanyById(String(showId.value))
    form.value.card = res.companyCardAssociationList.map((item: any) => {
        return {
            id: item.cardId,
            name: item.cardName,
            appId: item.appId,
            appKey: item.appKey,
            openFlag: item.openFlag,
        }
    })
    loading.value = false
})

const { isPending, mutateAsync: runDistributeCard } = useMutation({
    mutationFn: data => distributeCard(data),
    onSuccess: async (data) => {
        console.log('🚀 ~ distributecard ~ data:', data)
        ElMessage.success('保存成功')
        setTimeout(() => {
            emits('confirm')
            emits('update:modelValue', false)
        }, 1000)
    },
})

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const list = idList.value.reduce((acc, id) => {
                const area = form.value.card.map((item: any) => {
                    return {
                        companyId: id,
                        appKey: item.appKey,
                        appId: item.appId,
                        cardId: item.id,
                        cardName: item.name,
                        openFlag: item?.openFlag || 0,
                    }
                })
                return [...acc, ...area]
            }, [])
            console.log('🚀 ~ list ~ list:', list)

            runDistributeCard(list)
        }
        else {
            console.log('error submit!', fields)
        }
    })
}

function close(formEl: FormInstance | undefined) {
    formEl && formEl.resetFields()
    emits('update:modelValue', false)
}

function selectChange(val: any) {
    console.log('🚀 ~ selectChange ~ val:', val)
}
</script>

<template>
    <ElDialog v-model="modelValue"
              width="800"
              :close-on-click-modal="false"
              title="分配应用"
              @close="close(formRef)"
    >
        <ElForm ref="formRef"
                :model="form"
                label-width="auto"
                :rules="appRules"
                label-position="left"
        >
            <ElFormItem label="选择应用"
                        prop="card"
            >
                <el-select v-model="form.card"
                           multiple
                           :loading="loading"
                           value-key="id"
                           placeholder="请选择应用"
                           @change="selectChange"
                >
                    <el-option v-for="item in cardList"
                               :key="item.id"
                               :label="item.name"
                               :value="item"
                    />
                </el-select>
            </ElFormItem>

            <ElFormItem class="mgt-20">
                <div text-center
                     style="width:100%"
                >
                    <ElButton @click="close(formRef)">
                        取消
                    </ElButton>

                    <ElButton type="primary"
                              :loading="isPending"
                              @click="doSave(formRef)"
                    >
                        确定
                    </ElButton>
                </div>
            </ElFormItem>
        </ElForm>
    </ElDialog>
</template>
